# frozen_string_literal: true

require 'spec_helper'

RSpec.describe VulnerabilityExports::ExportDeletionWorker, type: :worker, feature_category: :vulnerability_management do
  describe '#perform' do
    let(:worker) { described_class.new }

    subject(:delete_vulnerability_export) { worker.perform(vulnerability_export_id) }

    context 'when vulnerability export does not exist' do
      let(:vulnerability_export_id) { nil }

      it 'does not raise exception' do
        expect { delete_vulnerability_export }.not_to raise_error
      end

      it 'does not delete any vulnerability export from database' do
        expect { delete_vulnerability_export }.not_to change { Vulnerabilities::Export.count }
      end
    end

    context 'when vulnerability export exists' do
      let_it_be(:vulnerability_export) { create(:vulnerability_export, :finished, :csv, :with_csv_file) }

      let(:vulnerability_export_id) { vulnerability_export.id }

      context 'when destroy can be performed successfully' do
        it 'destroys vulnerability export' do
          expect { delete_vulnerability_export }.to change { Vulnerabilities::Export.find_by_id(vulnerability_export.id) }.to(nil)
        end
      end

      context 'when destroy fails' do
        before do
          allow_any_instance_of(Vulnerabilities::Export).to receive(:destroy!).and_raise(ActiveRecord::Rollback)
        end

        it 'raises exception' do
          expect { delete_vulnerability_export }.to raise_error(ActiveRecord::Rollback)
        end
      end
    end
  end
end
